package com.keda.controller;

import com.keda.model.Product;
import com.keda.model.ProductDetail;
import com.keda.service.ProductService;
import net.sf.json.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/product")
public class ProductServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {

        // 1.获取参数
        String productId = request.getParameter("id");

        // 2. 调用Service查询数据
        ProductService productService = new ProductService();
        try {
            ProductDetail productDetail = productService.findById(productId);
            request.setAttribute("product", productDetail);

            // 添加历史记录
            productService.addToHistory(productDetail, request.getSession());

            // 3.跳转到详情页
            request.getRequestDispatcher("product-detail.jsp").forward(request, response);
        } catch (RuntimeException e) {
            request.setAttribute("error", e.getMessage());
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }

    }
}
